<template>
  <XenPageLayout
    title="请假出差详情"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
    :loading="loading"
    :error="hasError"
    @retry="loadLeaveDetail(Id)"
  >
    <!-- 内容区域 -->
    <view
      class="details-container"
      :class="{ 'has-audit-actions': isMyApprove }"
    >
      <!-- 详情内容 -->
      <view class="details-card">
        <view class="card-content">
          <!-- 使用动态详情组件 -->
          <XenDynamicDetailsCard
            :sections="formSections"
            :data="processedData"
            :field-mapping="fieldMapping"
            :get-image-url="getImageUrl"
            @preview-image="previewImage"
          />

          <!-- 审核时间线组件 - 所有用户都有权限查看 -->
          <XenAuditTimeline :steps="timelineData" />
        </view>
      </view>
    </view>

    <!-- 审核操作按钮组件 - 根据IsMyApprove字段控制显示 -->
    <XenAuditActions
      v-if="isMyApprove"
      ref="auditActionsRef"
      :actions="auditActions"
      @action="handleAuditAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { onLoad, onShareAppMessage } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicDetailsCard from "@/components/XenDynamicDetailsCard.vue";
import XenAuditTimeline from "@/components/XenAuditTimeline.vue";
import XenAuditActions from "@/components/XenAuditActions.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useLeaveInfo } from "./composables/useInfo";

import commonApi from "@/api/common";
import SysDailyLeaveRequestBillApi from "./api/index";
import type { QueryTimeline, WorkflowInfo } from "@/type/common";
import type { ISysDailyLeaveRequestBillVm } from "./api/interface";
import type { ICompanyItem } from "@/type/common";

// 获取详情页面的表单分组配置
const formSections = computed(() => getFormSectionsByPageType("details"));

// 页面状态
const Id = ref<string>("");
const hasError = ref<boolean>(false);

// 审核相关数据
const timelineData = ref<WorkflowInfo[]>([]);
const isMyApprove = ref<boolean>(false);
const auditLoading = ref<boolean>(false);
const auditActionsRef = ref();

// 公司和部门数据
const companyList = ref<ICompanyItem[]>([]);
const departmentList = ref<any[]>([]);

// 处理原始数据，将OrgId转换为公司名称，GroupId转换为部门名称
const processedData = computed(() => {
  if (!originalData.value) return null;

  const data = { ...originalData.value };

  // 如果有OrgId，将公司名称设置给Org.Name字段用于显示
  if (data.OrgId) {
    const companyName = getCompanyNameById(data.OrgId);
    if (companyName) {
      // 确保Org对象存在
      if (!data.Org) {
        data.Org = {};
      }
      // 设置公司名称到Org.Name，这样fieldMapping中的"Org.Name"就能获取到值
      data.Org.Name = companyName;
    }
  }

  // 如果有GroupId，将部门名称设置给Group.GroupName字段用于显示
  if (data.GroupId) {
    const departmentName = getDepartmentNameById(data.GroupId);
    if (departmentName) {
      // 确保Group对象存在
      if (!data.Group) {
        data.Group = {};
      }
      // 设置部门名称到Group.GroupName，这样fieldMapping中的"Group.GroupName"就能获取到值
      data.Group.GroupName = departmentName;
    }
  }

  return data;
});

// 创建API实例
const commonApiInstance = commonApi();
const api = SysDailyLeaveRequestBillApi();

// 使用请假出差申请信息 Composable
const {
  loading,
  originalData,
  getImageUrl,
  initializeOptions,
  loadLeaveDetail,
  fieldMapping,
} = useLeaveInfo();

// 根据公司ID获取公司名称
const getCompanyNameById = (orgId: string | null): string => {
  if (!orgId || !companyList.value.length) return "";

  const company = companyList.value.find((item) => item.Value === orgId);
  return company ? company.Text : "";
};

// 根据部门ID获取部门名称（递归查找，支持多级部门）
const getDepartmentNameById = (groupId: string | null): string => {
  if (!groupId || !departmentList.value.length) return "";

  // 递归查找部门
  const findDepartmentById = (departments: any[], id: string): any => {
    for (const dept of departments) {
      if (dept.ID === id || dept.Value === id) {
        return dept;
      }
      if (dept.Children && dept.Children.length > 0) {
        const found = findDepartmentById(dept.Children, id);
        if (found) return found;
      }
    }
    return null;
  };

  const department = findDepartmentById(departmentList.value, groupId);
  return department
    ? department.Text || department.GroupName || department.Name
    : "";
};

// 加载公司列表
const loadCompanyList = async () => {
  const response = await commonApiInstance.GetUserCompanies();
  if (response && Array.isArray(response)) {
    companyList.value = response;
  }
};

// 加载部门列表
const loadDepartmentList = async () => {
  const response = await commonApiInstance.GetParentsTree();
  if (response && Array.isArray(response)) {
    departmentList.value = response;
  }
};

// 审核操作按钮配置
const auditActions = computed(() => [
  {
    key: "approve",
    label: "同意",
    type: "primary" as const,
    icon: "checkmarkempty",
    primary: true,
    customStyle: "background: #409eff; color: #ffffff;",
    disabled: auditLoading.value,
  },
  {
    key: "reject",
    label: "拒绝",
    type: "danger" as const,
    icon: "closeempty",
    primary: true,
    customStyle: "background: #f56c6c; color: #ffffff;",
    disabled: auditLoading.value,
  },
]);

// 获取时间线数据
const getTimelineData = async () => {
  if (!Id.value) return;

  const params: QueryTimeline = {
    entityId: Id.value,
    entitytype: "HengTong.Model.Db.Bill.SysDailyLeaveRequestBill",
  };

  const response = await commonApiInstance.getTimeline(params);
  timelineData.value = response || [];
};

// 处理审核操作
const handleAuditAction = (action: any, remark?: string) => {
  console.log("审核操作:", action, "审批原因:", remark);

  switch (action.key) {
    case "approve":
      handleApprove(remark);
      break;
    case "reject":
      handleReject(remark);
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 审核通过
const handleApprove = (remark?: string) => {
  // 直接执行同意操作，因为审批原因已经在组件中收集
  performAudit("同意", remark);
};

// 审核拒绝
const handleReject = (remark?: string) => {
  // 直接执行拒绝操作，因为拒绝原因已经在组件中收集
  performAudit("拒绝", remark);
};

// 执行审核操作
const performAudit = async (actionName: string, remark?: string) => {
  if (!originalData.value) {
    uni.showToast({
      title: "数据异常，请刷新页面重试",
      icon: "none",
    });
    return;
  }

  auditLoading.value = true;

  // 构造请求参数
  const requestData: ISysDailyLeaveRequestBillVm = {
    ActionName: actionName,
    Entity: originalData.value,
    IsMyApprove: isMyApprove.value,
  };

  // 调用审核接口
  const result = await api.approve(requestData);

  if (result) {
    // 关闭审批弹窗（同意和拒绝操作都需要关闭）
    if (actionName === "拒绝" || actionName === "同意") {
      auditActionsRef.value?.closeRejectPopup();
    }

    uni.showToast({
      title: `${actionName}成功`,
      icon: "success",
    });

    // 延迟1秒后返回页面
    setTimeout(() => {
      uni.navigateBack({
        success: () => {
          console.log("返回页面成功");
        },
        fail: () => {
          console.log("返回页面失败，尝试跳转到工作台");
          uni.reLaunch({
            url: "/pages/work/work",
            fail: () => {
              console.log("跳转工作台失败");
            },
          });
        },
      });
    }, 1000);
  }

  auditLoading.value = false;
};

// 预览图片 - 统一的图片预览函数
const previewImage = (fileId: string | null) => {
  if (!fileId) {
    uni.showToast({
      title: "图片无效",
      icon: "none",
    });
    return;
  }

  const imageUrl = getImageUrl(fileId);
  if (!imageUrl) {
    uni.showToast({
      title: "图片无效",
      icon: "none",
    });
    return;
  }

  uni.previewImage({
    urls: [imageUrl],
    current: imageUrl,
    fail: () => {
      uni.showToast({
        title: "预览图片失败",
        icon: "none",
      });
    },
  });
};

// 获取分享标题
const getShareTitle = () => {
  if (originalData.value?.BillCode) {
    return `请假出差${originalData.value.BillCode}`;
  }
  return "请假出差详情";
};

// 获取分享路径
const getSharePath = () => {
  if (Id.value) {
    return `/subpkg-hr-sysdailyleaverequestbill/details?id=${Id.value}`;
  }
  return "/subpkg-hr-sysdailyleaverequestbill/index";
};

// 页面加载时获取路由参数
onLoad((options) => {
  if (options?.id) {
    Id.value = options.id;
  } else {
    uni.showToast({
      title: "缺少ID参数",
      icon: "none",
    });
  }

  // 设置微信小程序分享功能
  // #ifdef MP-WEIXIN
  onShareAppMessage(() => {
    return {
      title: getShareTitle(),
      path: getSharePath(),
      imageUrl: "", // 可以设置分享图片
    };
  });
  // #endif
});

// 页面挂载后加载数据
onMounted(async () => {
  // 并行加载选项数据、公司列表和部门列表
  await Promise.all([
    initializeOptions(),
    loadCompanyList(),
    loadDepartmentList(),
  ]);

  if (Id.value) {
    const result = await loadLeaveDetail(Id.value);
    if (!result.success) {
      hasError.value = true;
    } else {
      // 设置审核权限标识
      isMyApprove.value = result.isMyApprove || false;

      // 加载成功后，获取时间线数据
      await getTimelineData();
    }
  }
});
</script>

<style lang="scss" scoped>
.details-container {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  min-height: calc(100vh - 80px);

  // 当有审核操作组件时，添加底部内边距避免遮挡
  &.has-audit-actions {
    padding-bottom: 100px; // 为审核操作组件预留空间
  }
  .details-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .card-header {
      padding: 20px 24px;
      border-bottom: 1px solid #f0f0f0;

      .form-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 4px;
      }

      .form-subtitle {
        font-size: 14px;
        color: #666;
      }
    }

    .card-content {
      padding: 24px;
    }
  }
}
</style>
